#!/usr/local/bin/perl

# Ok, I will be the client.. what should I do?!

# keep running..
# read plugins.conf, find out what plugins to run, and when
# run plugins

require ('/root/scuderia_client/plugins/plugins.conf');


sub report_results {
print "represult called\n";
    my $to_report = @_;
    my $master_ip = '127.0.0.1';
    my $master_port = '7801';
    use IO::Socket;
    my $sock = new IO::Socket::INET (
					PeerAddr => $master_ip,
					PeerPort => $master_port,
					Proto	=> 'tcp',
					);
		die "couldn't create socket: $!\n" unless $sock;
    print $sock "str @_";
}


sub read_process_results {
print "plug exec called\n";

# ok in the alpha version, I will fork each plugin one by one and wait for it's return :/:P
    $line = '';
    open(STATUS, "@_ 2>&1 |") || die "can't fork: $!";
	while (<STATUS>) {
	    $line .= $_;
	}
    close STATUS || die "bad bad subproc: $! $?";
    return "$line";
}

# predef
my $timeout_for_plug;
my $newval;
my $report_val;
my $line;

my $timer = 1;
for (;;) {
print "----------------------------Cycle #$timer called\n";
# this few lines to initialize all plugins enabled
    foreach $plugname ( keys %plugins_enabled ) {
	    print "new foreach\n";
	    $timeout_for_plug = $plugins_enabled{$plugname};
	    $newval = $timer % $timeout_for_plug;
	if ( $newval eq 1 ) {
	    $line = '';
	    $report_val = '';
	    $report_val = read_process_results("/root/scuderia_client/plugins/$plugname");
	    print "Calling reporting for $plugname\n";
	    report_results($report_val);
	} 
    }
print "----------------------------Cycle #$timer ended\n";

sleep(1);
    if ( $timer >= 10 ) {
	$timer = 1;
    } else {
	$timer = $timer + 1;
    }
}
